﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TruckWatch.Cloud.BusinessLogic;
using TruckWatch.Cloud.Models;
using TruckWatch.Cloud.Models.ViewModels;
using Mvc30WebRole1.Util;

namespace Mvc30WebRole1.Controllers
{
  
    [NoCache]
    public partial class ServicesController : Controller
    {

        #region UpdateLocation

        [HttpPost]
        public ActionResult UpdateLocation(string id)
        {
            try
            {
                TripPointNEF tripPoint = new TripPointNEF();

                // Read Values
                DriverCredential credential = GetDriverCredentialFromQueryString(id);

                tripPoint.Latitude = CommonUtil.TryParseDouble(Request.Form["Latitude"]);
                tripPoint.Longitude = CommonUtil.TryParseDouble(Request.Form["Longitude"]);

                // Validate
                this.ValidateModel(tripPoint);

                // Write to database
                ServiceBL.UpdateLocation(credential, tripPoint);

                // Return view
                ViewBag.UserId = credential.UserId;
                ViewBag.Success = true;
                return View(tripPoint);
            }
            catch (Exception ex)
            {
                ViewBag.Success = false;
                ViewBag.ErrorMsg = ex.Message;
                return View();
            }
        }

        #endregion

        #region GetAllDriverLocations


        public JsonResult GetAllDriverLocations(double latitude, double longitude)
        {
            var ret = DriverBL.GetAllDriverLocations(new GeoPoint(latitude, longitude), false);
            return Json(ret, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetAllDriverLocationsNearMe(double latitude, double longitude, double radius, bool IncludeAddress)
        {
            List<DriverLocation> ret = DriverBL.GetAllDriverLocationsNearMe(new GeoPoint(latitude, longitude), radius, IncludeAddress);

            return Json(ret, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetNthClosestDriverLocationToMe(double latitude, double longitude, int nth)
        {
            DriverLocation ret = DriverBL.GetNthClosestDriverLocationToMe(new GeoPoint(latitude, longitude), nth);

            return Json(ret, JsonRequestBehavior.AllowGet);
        }

        #endregion

    }
}
